package service

import (
	"chatBot/dao"
	"chatBot/share"
	"encoding/json"
	"errors"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
	"strconv"
	"strings"
)

const (
	FeedbackKey = "feedback"
	ReviewKey   = "review"

	GetMessage      = "/message/list"
	MessageFeedback = "/message/feedback"
)

type feedback struct {
	Messgage string `json:"message"`
	Rating   int    `json:"rating"`
}

// 配置WebSocket升级器
var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		// 允许所有跨域请求（生产环境应更严格限制）
		return true
	},
}

func handleWebSocket(w http.ResponseWriter, r *http.Request) {
	// 升级HTTP连接到WebSocket
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println("Upgrade error:", err)
		return
	}
	defer conn.Close()

	log.Printf("Client connected:%v", conn.RemoteAddr())

	// 读取握手包
	_, msg, err := conn.ReadMessage()
	if err != nil {
		log.Println("握手包读取失败:", err)
		return
	}

	var hs share.HandshakeReq
	if json.Unmarshal(msg, &hs) != nil {
		conn.WriteJSON(share.HandshakeResp{
			Status:  400,
			Message: "无效握手格式",
		})
		return
	}

	// todo: 验证逻辑

	// 用户握手成功，插入customer表
	customer := dao.Customer{
		Name:  hs.Username,
		Token: hs.Token,
	}
	id, err := dao.InsertCustomer(customer)
	if err != nil {
		conn.WriteJSON(share.HandshakeResp{
			Status:  500,
			Message: "内部错误",
		})
		return
	}
	hs.CustomerId = id

	// 发送成功响应
	conn.WriteJSON(share.HandshakeResp{
		Status:  200,
		Message: "认证成功，欢迎 " + hs.Username,
	})

	// 处理消息
	for {
		var msg share.WebsockMsg
		// 读取客户端消息
		messageType, message, err := conn.ReadMessage()
		if err != nil {
			if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
				log.Printf("Info: %v", err)
			}
			break
		}

		log.Printf("Received: %s len(message):%v", message, len(message))
		err = json.Unmarshal(message, &msg)
		if err != nil {
			if err := conn.WriteMessage(messageType, []byte(err.Error())); err != nil {
				log.Println("Write error:", err)
				break
			}
		}

		if len(msg.Content) > 0 {
			msg.Content = msg.Content[:len(msg.Content)-1]
		}
		log.Printf("content: %s len():%v", msg.Content, len(msg.Content))

		rsp, err := handleMessage(hs, msg.Content)

		if err != nil {
			if err := conn.WriteMessage(messageType, []byte(err.Error())); err != nil {
				log.Println("Write error:", err)
				break
			}
		}

		// 回显消息给客户端
		if err := conn.WriteMessage(messageType, []byte(rsp)); err != nil {
			log.Println("Write error:", err)
			break
		}
	}

	log.Println("Client disconnected:", conn.RemoteAddr())
}

func handleMessage(hs share.HandshakeReq, msg string) (string, error) {
	// 处理消息查询
	if strings.Contains(strings.ToLower(msg), GetMessage) {
		args := strings.Split(msg, " ")
		if len(args) != 3 {
			rsp := "The number of parameters is incorrect. example:/message/list 10 0"
			log.Println(rsp)
			return "", errors.New(rsp)
		}

		pageSize, _ := strconv.Atoi(args[1])
		offset, _ := strconv.Atoi(args[2])
		log.Printf("pageSize:%v", pageSize)
		log.Printf("offset:%v", offset)

		if pageSize <= 0 || offset < 0 {
			rsp := "pageSize must be > 0 and offset >= 0, example:/message/list pageSize offset"
			log.Println(rsp)
			return "", errors.New(rsp)
		}

		msgList, err := dao.GetMessageList(hs.CustomerId, pageSize, offset)
		if err != nil {
			return "", err
		}

		log.Printf("msgList:%v", msgList)

		data, err := json.Marshal(msgList)
		if err != nil {
			return "", err
		}
		return string(data), nil
	}

	// 处理feedback消息
	if strings.Contains(strings.ToLower(msg), MessageFeedback) {
		//获取消息内容，去掉/message/feedback
		msg = strings.Replace(msg, MessageFeedback, "", -1)
		var f feedback
		err := json.Unmarshal([]byte(msg), &f)
		if err != nil {
			return "", err
		}

		log.Printf("feedback msg:%v hs:%v", msg, hs)

		if f.Rating < 1 || f.Rating > 5 {
			rsp := "Please rate your experience from 1-5, example:/message/feedback {\"message\": \"aaaaa\", \"rating\": 5}"
			log.Println(rsp)
			return "", errors.New(rsp)
		}

		// todo: 情绪分析：positive, neutral, or negative

		feedback := dao.Feedback{
			CustomerID: hs.CustomerId,
			Message:    f.Messgage,
			Rating:     f.Rating,
			Analysis:   "positive",
		}

		err = dao.InsertFeedback(feedback)
		if err != nil {
			log.Fatal("Insert feed back message error:", err)
			return "", err
		}

		return "Thanks for your feedback!", nil
	}

	// 插入消息表
	message := dao.Message{
		CustomerID: hs.CustomerId,
		Message:    msg,
		Sender:     "customer",
	}
	err := dao.InsertMessage(message)
	if err != nil {
		log.Fatal("InsertMessage error:", err)
		return "", err
	}

	// 匹配feedback关键字
	if strings.Contains(strings.ToLower(msg), FeedbackKey) || strings.Contains(strings.ToLower(msg), ReviewKey) {
		rsp := "Please rate your experience from 1-5"

		// 回复消息写入消息库
		message.Message = rsp
		message.Sender = "bot"
		err := dao.InsertMessage(message)
		if err != nil {
			log.Fatal("InsertMessage error:", err)
			return "", err
		}

		return rsp, nil
	}

	// todo: 调用AI接口，或者自己整理的回复列表
	//reply, err := api.WenxinChat(msg)
	//if err != nil {
	//	log.Println("Error:", err)
	//	return "", errors.New(err.Error())
	//}
	//log.Println("文心回复:", reply)

	// 回复消息写入消息库
	//message.Message = reply
	//message.Sender = "bot"
	//err = dao.InsertMessage(message)
	//if err != nil {
	//	log.Fatal("InsertMessage error:", err)
	//	return "", err
	//}

	return msg, nil
}

// 获取消息列表
func handleMessageList(w http.ResponseWriter, r *http.Request) {

}
